from django.db.models import F, Max
from rest_framework import serializers
from django.forms import model_to_dict
from api import models


class MoneyTypeModelSerializer(serializers.ModelSerializer):
    # 支持类型渲染序列化器
    class Meta:
        model = models.DepositRecord
        fields = ['id', 'get_deposit_type_display', 'amount']


class AuctionItemPriceModelSerializer(serializers.ModelSerializer):
    """获取最大出价&&竞价序列化器"""
    user = serializers.CharField(read_only=True)
    price = serializers.CharField(write_only=True)

    class Meta:
        model = models.BidRecord
        fields = ['price', 'user']

    def validate(self, attrs):
        # 校验商品
        item_id = self.context['request'].GET.get('item')
        if not item_id:
            raise serializers.ValidationError('商品不合法')
        auction_query = models.AuctionItem.objects.filter(status=3, is_delete=False, is_show=True, id=item_id)
        if not auction_query:
            raise serializers.ValidationError('商品消息不合法')
        # 校验价格是否存在
        price = int(attrs.get('price'))
        if not price:
            raise serializers.ValidationError('价格不能为空')
        # 校验价格是否数据库存在
        price_query = models.BidRecord.objects.filter(status=1, is_delete=False, is_show=True, item_id=item_id)
        exist_price = price_query.filter(price=price)
        if exist_price:
            raise serializers.ValidationError('该价格已存在')
        # 当前价格是否大于起始价
        start_price = auction_query.first().start_price
        if price < start_price:
            raise serializers.ValidationError('出价不能小于起始价')
        # 校验价格是否以规定加价出现
        unit = auction_query.first().unit
        # print(unit)
        if price % unit != 0:
            raise serializers.ValidationError('加价幅度不允许')
        # 校验价格是否合法(目前最高)
        # 找到最大的价格
        old_price = price_query.aggregate(max_price=Max('price')).get('max_price')
        if not old_price:
            return attrs
        if price < old_price:
            raise serializers.ValidationError('当前价格低于最高价格')
        return attrs


class OrderModelSerializer(serializers.ModelSerializer):
    auction = serializers.SerializerMethodField()
    auction_item = serializers.SerializerMethodField()
    cover = serializers.CharField(source='auction_item.cover')
    create_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S')

    class Meta:
        model = models.Order
        fields = ['id', 'uid', 'status', 'create_time', 'price', 'cover', 'auction', 'auction_item']

    def get_auction(self, obj):
        auc_dic = model_to_dict(obj.auction, fields=['id', 'title'])
        return auc_dic

    def get_auction_item(self, obj):
        auc_dic = model_to_dict(obj.auction_item, fields=['id', 'title'])
        return auc_dic

    # def get_cover(self, obj):
    #     item_image = obj.auction_item.cover
    #     return item_image
